<template>
	<view>
		<view class="container">
			<view class="cT">购物车</view>
			<!-- 包裹内容 -->
			<view v-show="shopCartList.length > 0" class="cB">
				<view class="cBItem" v-for="shopCart in shopCartList" :key="shopCart._id">
					<view class="cBItemB">
						<u-checkbox v-model="shopCart.checked" @change="changeChecked($event,shopCart._id)"
							shape="circle" active-color="#fdd100" :disabled="shopCart.num===0" icon-size="10rpx">
						</u-checkbox>
					</view>
					<view class="content">
						<image :src="shopCart.img" mode=""></image>
						<view class="contentB">
							<view class="text">{{shopCart.name}}</view>
							<view class="tags">
								<text >{{shopCart.attr}}</text>
							</view>
							<view class="priceAndAdd">
								<view class="price">
									￥{{shopCart.price}}
								</view>
								<u-number-box :min="0" :max="200" v-model="shopCart.num"
									@plus="addOrRaduce($event,shopCart)" @minus="addOrRaduce($event,shopCart)">
								</u-number-box>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view v-show="shopCartList.length > 0" class="footer">
				<view class="allSelect">
					<u-checkbox v-model="checkAll" shape="circle" active-color="#fdd100" icon-size="10rpx"> 全选
					</u-checkbox>
				</view>
				<view class="total">
					<view>合计:</view>
					<view>
						<text>￥</text>
						<text>{{total.toFixed(2)}}</text>
					</view>
				</view>
				<u-button type="error" shape="circle" :custom-style="{width:'200rpx',height:'100%'}"
					@click="createOrder">购买</u-button>
			</view>
			<view v-show="shopCartList.length === 0" class="empty">
				<image src="../../static/images/common/empty.png"></image>
				<view>购物车为空</view>
			</view>
			<view class="likeList">
				<view class="title">
					<text>猜你喜欢</text>
				</view>
				<view class="likeContent" >
					<view class="likeItem" v-for="like in likeList" :key="like._id" @click="goDetail(like)">
						<image :src="like.img"></image>
						<view class="likeItemText">
							{{like.name}}
						</view>
						<view class="likeItemPrice">
							<view class="price">
								<text>￥</text>
								<text>{{like.price.toFixed(2)}}</text>
							</view>
							<view class="sold">
								已售{{like.sales}}件
							</view>
						</view>
					</view>
				</view>
			</view>
			<MyLoading v-model:lodingType="lodingType"/>
			<u-modal v-model="showModal" content="确定移除吗" @cancel="cancelCart" :show-cancel-button="true"
				@confirm="removeCart"></u-modal>
			<tarbar :current="2"></tarbar>
		</view>
	</view>
</template>
<script setup>
	import {
		onShow,
		onLoad,
		onReachBottom
	} from "@dcloudio/uni-app"
	import {
		ref,
		computed,
		watch,
		reactive
	} from 'vue'
	import tarbar from '../../components/tarbar/tarbar.vue'
	import {
		userStore
	} from '../../stores/userInfo/userInfo.js'
	import {
		shopCart,
		home
	} from '@/api'
	import  MyLoading  from '@/components/MyLoading'
	let shopCartList = ref([])
	let userInfo = reactive({})
	let user = userStore()
	watch(() => user.updateShopCart, () => {
		userInfo = user.userInfo
		getShopCart()
	}, {
		immediate: true
	})
	// 选中的参数
	let checkedParams = reactive({
		_id: '',
		checked: true
	})
	// 这是获得 步进器更改的值
	let params = reactive({
		_id: '',
		num: ''
	})
	let addOrRaduceFlag = ref(true)
	// 显示模态框
	let showModal = ref(false)
	let remove_id = ref('')
	// 移除购物车
	function removeCart() {
		shopCart.reqRemoveCart({
			_id: params._id
		}).then(() => {
			uni.$u.toast('删除成功')
			getShopCart()
		})
	}
	// 点击取消
	function cancelCart() {
		checkedParams._id = params._id
		checkedParams.checked = true
		sendChangeCart().then(() => {
			getShopCart()
		})
	}
	// 购物车加减
	function addOrRaduce($e, shopCart) {
		let {
			_id,
			num
		} = shopCart
		params = {
			_id,
			num: $e.value
		}
		if ($e.value === 0) {
			showModal.value = true
		}
		if ($e.value === 1) {
			checkedParams._id = _id
			checkedParams.checked = false
			sendChangeCart().then(() => {
				getShopCart()
			})
		}
		if (addOrRaduceFlag) {
			addOrRaduceFlag.value = false
			sendAddOrReduce()
		}

	}
	// send购物车加减
	function sendAddOrReduce() {
		shopCart.reqAddOrReduce(params).then(res => {
			addOrRaduceFlag.value = true
		}).catch(() => {
			addOrRaduceFlag.value = true
		})
	}
	// 全选
	let checkAll = computed({
		get: () => {
			if (shopCartList.value.length === 0) {
				return false
			}
			return shopCartList.value.every(item => item.checked)
		},
		set: (value) => {
			let _id = []
			shopCartList.value.forEach(item => {
				if (item.checked === value) return
				_id.push(item._id)
			})
			let data = {
				_id,
				checked: !value
			}
			sendAllchangeCart(data).then(res => {
				if (res === 'ok') {
					shopCartList.value.forEach(item => {
						_id.forEach(v => {
							if (item._id === v) {
								item.checked = value
							}
						})
					})
				} else {
					uni.$u.toast('全选失败')
				}
			})
		}
	})
	// 总价
	let total = computed(() => {
		// forEach 写法
		// let total = 0
		// shopCartList.value.forEach(item => {
		// 	if (item.checked) {
		// 		total += item.num * item.price
		// 	}
		// })
		// reduce 写法
		let total = shopCartList.value.reduce((previous, current) => previous += current.checked ? current.num *
			current.price : 0, 0)
		return total
	})
	// 更改选中状态
	async function changeChecked(e, _id) {
		checkedParams._id = _id
		checkedParams.checked = !e.value
		sendChangeCart()
	}
	// 发送更改所有的状态 
	async function sendAllchangeCart(data) {
		let res = await shopCart.reqAllChangeCart(data)
		if (res.code === 1) {
			return 'ok'
		} else {
			return 'faild'
		}
	}
	// 发送更改选中状态
	async function sendChangeCart() {
		let res = await shopCart.reqChangeChecked(checkedParams)
		if (res.code === 1) {
			return 'ok'
		} else {
			return 'faild'
		}
	}
	// 获取购物车列表
	function getShopCart() {
		let {
			_id: uid
		} = userInfo
		shopCart.reqShopCartList({
			uid
		}).then(res => {
			if (res.code === 1) {
				res.data = res.data.map(v => {
					return {
						...v,
						price: parseFloat(v.price).toFixed(2)
					}
				})
				shopCartList.value = res.data
			}
		})
	}
	//createOrder 创建订单
	function createOrder() {
		if (total.value === 0) {
			uni.$u.toast('购物车不能为空')
			return
		}
		let cart_id = encodeURI(JSON.stringify(shopCartList.value.map(v => v._id)))
		uni.navigateTo({
			url: `/pages/order/CreateOrder/CreateOrder?cart_id=${cart_id}`
		})
	}

	let likePramas = reactive({
		skip: 0,
		limit: 4
	})
	let likeList = ref([])
	// 加状态 more 更多  loading 加载中 loaded 数据没有了
	let lodingType = ref('more')
	function getLikeList() {
		lodingType.value = 'loading'
		likePramas.skip = likeList.value.length
		home.reqLike(likePramas).then(res => {
			if (res.code === 1) {
				let arr = likeList.value
				arr.push(...res.data)
				likeList.value = arr
				if (likeList.value.length >= res.count) {
					lodingType.value = 'loaded'
				} else {
					lodingType.value = 'more'
				}
			}
		})
	}
	// 去商品详情
	function goDetail(like) {
		let { _id } = like
		uni.navigateTo({
			url: `/pages/goodsDetail/goodsDetail?goods=${_id}`
		})
	}
	onReachBottom(() => {
		if(lodingType.value === 'loaded' || lodingType.value === 'loading') return
		getLikeList()
	})
	onLoad(() => {
		getLikeList()
	})
	// 不用自带的tabbar
	onShow(() => {
		// 判断有没有登录
		let user = userStore()
		if (!user.userInfo._id) {
			uni.navigateTo({
				url: '/pages/user/login/login'
			})
			return
		}
		userInfo = user.userInfo
		uni.hideTabBar({
			animation: false
		})
	})
</script>

<style lang="scss" scoped>
	.container {
		height: 100%;
		padding-top: 50rpx;
		padding-bottom: 100rpx;
		position: relative;
		background-color: #f5f5f5;

		.cT {
			height: 80rpx;
			line-height: 80rpx;
			background-color: #ffffff;
			text-align: center;
		}

		.cB {
			background-color: #ffffff;
			border-top-left-radius: 25rpx;
			border-top-right-radius: 25rpx;
			margin: 20rpx;
			padding: 20rpx 0;
			overflow: auto;
			height: calc(100% - 190rpx);

			.cBItemB {
				margin-left: 30rpx;
			}

			.cBItem {
				display: flex;
				align-items: center;

				.content {
					flex: 1;
					display: flex;
					padding: 20rpx;
					border-bottom: 3rpx solid #f9f9f9;

					image {
						width: 200rpx;
						height: 200rpx;
					}

					.contentB {
						flex: 1;
						margin-left: 25rpx;
						display: flex;
						flex-direction: column;
						justify-content: space-between;
					}

					.text {
						font-size: 25rpx;
						display: -webkit-box;
						-webkit-line-clamp: 2;
						-webkit-box-orient: vertical;
						text-overflow: ellipsis;
						overflow: hidden;
					}

					.tags {
						font-size: 15rpx;

						text {
							background-color: #eee;
							color: #878787;
							padding: 8rpx;
							margin-right: 15rpx;

							&:last-child {
								margin: 0;
							}
						}
					}

					.priceAndAdd {
						display: flex;
						justify-content: space-between;
						align-items: center;

						.price {
							color: red;
						}

					}
				}
			}
		}

		.footer {
			box-sizing: border-box;
			position: fixed;
			height: 80rpx;
			bottom: 100rpx;
			left: 0;
			right: 0;
			padding: 5rpx 20rpx;
			background-color: #ffffff;
			display: flex;
			justify-content: space-between;
			align-items: center;
			z-index: 9999;
			.total {
				@include flex1();
				letter-spacing: 1rpx;

				view:last-child {
					margin-left: 5rpx;
					display: flex;
					justify-content: center;
					align-items: baseline;
					color: red;

					text:first-child {
						font-size: 18rpx;

					}
				}
			}
		}

		.empty {
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			image {
				width: 170rpx;
				height: 200rpx;
			}

			view {
				font-size: 15rpx;
				color: #878787;
			}
		}
	}

	.likeList {
		padding: 15rpx;
		
		.title {
			margin: 20rpx 0;
			font-size: 35rpx;
			font-weight: bold;
			display: flex;
			justify-content: center;
			background-image: linear-gradient(135deg,#fccf31,#f55555);
			background-clip: text;
			color: transparent
		}

		.likeContent {
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;

			.likeItem {
				width: 48%;
				padding: 15rpx 15rpx 20rpx 15rpx;
				background-color: #fff;
				display: flex;
				flex-direction: column;
				margin-bottom: 15rpx;
				border-radius: 10rpx;

				image {
					width: 100%;
					height: 350rpx;
				}

				.likeItemText {
					font-size: 30rpx;
					font-weight: 550;
					display: -webkit-box;
					-webkit-line-clamp: 2;
					-webkit-box-orient: vertical;
					text-overflow: ellipsis;
					overflow: hidden;
				}

				.likeItemPrice {
					margin: 15rpx 0;
					display: flex;
					justify-content: space-between;
					align-items: center;

					.price {
						font-size: 30rpx;
						color: red;

						text:first-child {
							font-size: 20rpx;
						}
					}

					.sold {
						color: #a1a1a1;
					}
				}
			}
		}
	}

	uni-button {
		margin: 0;
	}
</style>
